import java.util.Iterator;


public class MyHeaderList <T> implements HeaderList<T>{

	private class Node{
		private T head;
		private Node tail;
		
		private Node(T head, Node tail){
			this.head=head;
			this.tail=tail;
		}		
		
		private boolean hasNext(){
			return tail==null;
		}
	}
	
	private class MyIterator implements Iterator<T>{
		private Node current;
		private Node previous;
		
		private MyIterator(){
			this.previous=null;
			current=first;
		}
		
		public boolean hasNext() {
			if(current==null){
				return false;
			}
			return current.tail!=null;
		}

		public T next() {
			if(hasNext()){
				this.previous=current;
				current=current.tail;
				return current.head;
			}
			return null;
		}

		public void remove() {
			if(current==null){
				return;
			}
			previous.tail=current.tail;
			current.tail=null;
		}
		
	}
	
	private int size;
	private Node first;
	private Node previous=null;
	
	public MyHeaderList(){
		first=null;
		size=0;
	}
	
	public void add(T elem) {
		Node current=first;
		if(size==0){
			first=new Node(elem,null); 
			size++;
			return;
		}
		while(current.hasNext()){
			current=current.tail;
		}
		current.tail=new Node(elem,null);
		size++;
	}

	private Node get(T elem){		
		Node n;
		do{
			n=nextNode();
		}
		while(!isEmpty() && n!=null  );
		
		return n;
	}
	
	public boolean contains(T elem) {
		return get(elem)!=null;
	}

	public boolean isEmpty() {
		return size==0;
	}

	private Node nextNode(){
		Node current=first;
		if(isEmpty()){
			return null;
		}
		previous=current;
		current=current.tail;
		if(current==null){
			return null;
		}
		return current;
	}
	
	public T next() {
		Node next=nextNode();
		if(next==null){
			return null; 
		}
		return next.head;
	}

	public boolean remove(T elem) {
		Node toRemove=get(elem);
		if(toRemove==null){
			return false;
		}
		previous.tail=toRemove.tail;
		toRemove.tail=null;
		previous=null;
		return true;
	}

	public void reset() {
		first=null;
		previous=null;
		size=0;
	}

	public Iterator<T> iterator() {
		return new MyIterator();
	}

}
